import urllib2
from StringIO import StringIO
from leancloud import Query, Object, File

def saveFile(classname, oName, nName, count=None):
    if isinstance(oName, list) and len(oName)!=len(nName):
        return 'Len of oName, nName not equal'
    items = Query(Object.extend(classname)).ascending('updatedAt').find()
    c = 0
    for item in items:
        c += 1
        switch = False
        if isinstance(oName, list):
            for i in xrange(len(oName)):
                url = item.get(oName[i])
                if url and not item.get(nName[i]):
                    setFile(item, url, nName[i])
                    switch = True
                else:
                    print c, 'Item', nName[i], url, 'NoUrl or have nName Value'
        else:
            url = item.get(oName)
            if url and not item.get(nName):
                setFile(item, url, nName)
                switch = True
            else:
                print c, 'Item', nName, url, 'NoUrl or have nName Value'
        if switch:
            item.save()
            print c, 'Item Save Done!'
        else:
            print c, 'Item no need Save!'
        if count and c >= count:
            return
        # return
        
def setFile(item, url, nName):
    ret = urllib2.urlopen(url)
    filename = url.rsplit('/', 1)[-1]
    io = StringIO(ret.read())
    f = File(filename, io)
    item.set(nName, f)
    
if __name__ == '__main__':
    import leancloud
    leancloud.init('m3vGPBDTLcIBYncljScwWGaQ', master_key='Q1SCs9WsR1XxBUm8ExkthOVb')
    # saveFile('Agm_Product_beta', ['img', 'img_ch', 'img_pz', 'img_sm'], ['imgfile', 'imgfile_ch', 'imgfile_pz', 'imgfile_sm'])